﻿namespace Yz.Core.Extensions
{
    public static class NumberExtension
    {
        public static int ToInt<T>(this T obj)
        {
            var i = 0;
            if (obj != null)
            {
                var str = obj.ToString();
                int.TryParse(str, out i);
            }

            return i;
        }

        public static float ToFloat<T>(this T obj)
        {
            float i = 0;
            if (obj != null)
            {
                var str = obj.ToString();
                float.TryParse(str, out i);
            }

            return i;
        }

        /// <summary>
        ///     返回Float保留两位小数
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public static float ToFloatTwoDecimal(this float num)
        {
            var res = float.Parse(num.ToString("f2"));
            return res;
        }

        /// <summary>
        ///     Int返回字符串，缺少位数补0
        /// </summary>
        /// <param name="num">需要转换的整数</param>
        /// <param name="digit">保留几位有效数字</param>
        /// <returns></returns>
        public static string ToNumString(this int num, int digit = 2)
        {
            var str = num.ToString().PadLeft(digit, '0');
            return str;
        }

        public static bool ToBoolt<T>(this T obj)
        {
            var b = false;
            if (obj != null)
            {
                var str = obj.ToString();
                bool.TryParse(str, out b);
            }

            return b;
        }
    }
}
